package com.xing.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//操作数据库的基本类
public class BaseDao {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;


    //静态代码块，类加载的时候就初始化了
    static {
        Properties properties = new Properties();
        //通过类加载器读取相对应的资源
        InputStream inputStream = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        driver= properties.getProperty("driver");
        url= properties.getProperty("url");
        username= properties.getProperty("username");
        password= properties.getProperty("password");
    }
    //获取数据库的连接
    public Connection getConnection() throws ClassNotFoundException, SQLException {

        Class.forName(driver);
        connection = DriverManager.getConnection(url, username, password);
        return connection;
    }

    //查询
    public ResultSet execute(String sql, Object[] objects) throws SQLException, ClassNotFoundException {
        preparedStatement = this.getConnection().prepareStatement(sql);
        if (objects != null) {
            for (int i = 0; i < objects.length; i++) {
                preparedStatement.setObject((i + 1), objects[i]);
            }
        }
        resultSet = preparedStatement.executeQuery();
        return resultSet;
    }
    //增删改
    public int update(String sql,Object[] objects) throws SQLException, ClassNotFoundException {
        int result = 0;
        PreparedStatement preparedStatement = this.getConnection().prepareStatement(sql);
        if (objects != null) {
            for (int i = 0; i < objects.length; i++) {
                preparedStatement.setObject((i + 1), objects[i]);
            }
        }
         result= preparedStatement.executeUpdate();
        return result;
    }
    //释放资源
    public void closeAll(){
            try {
                if (resultSet != null){
                    resultSet.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
    }
}
